/*
 * msg_coder.cpp
 *
 *  Created on: Jan 13, 2014
 *      Author: killerg
 */




#include "msg_coder.h"

static uint8_t* s_code_table = NULL;
static uint32_t s_code_table_size = 1024;

static int32_t step_rand(int32_t seed) {
    seed = seed * 1103515245L + 12345L;

    return (seed >> 1) & 2147483647L;
}

bool init_code_table() {
    s_code_table = (uint8_t*)malloc(s_code_table_size);
    uint32_t seed = 0;
    for (uint32_t i=0; i<s_code_table_size; ++i) {
        seed = (uint32_t)step_rand(seed);
        s_code_table[i] = (uint8_t)seed;
    }

    return true;
}

void destroy_code_table() {
    free(s_code_table);
}

void encmsg(int idx, uint8_t* buffer, size_t buffer_size) {
    size_t code_idx = (idx + buffer_size) % s_code_table_size;
    for (int i=0; i<buffer_size; ++i, ++code_idx) {
        if (code_idx >= s_code_table_size)
            code_idx -= s_code_table_size;

        buffer[i] ^= (uint8_t)s_code_table[code_idx];
    }
}
